package com.ziyia.retrofittest;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Layout;
import android.util.Log;
import android.view.View;
import android.widget.Toast;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.time.LocalDate;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.DELETE;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;
import retrofit2.http.Path;
import retrofit2.http.Query;

public class MainActivity extends AppCompatActivity {

    private static final int FROMAIBUM = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case FROMAIBUM:

                if (resultCode == Activity.RESULT_OK && data != null) {
                    Toast.makeText(MainActivity.this, "功能未完成", Toast.LENGTH_SHORT).show();
                    Uri uri = data.getData();
                    Log.d("Uri", uri.toString());
                    String[] filePathColumns = {MediaStore.Images.Media.DATA};
                    Cursor cursor = getContentResolver().query(uri, filePathColumns, null, null, null);
                    cursor.moveToFirst();
                    String path = cursor.getString(cursor.getColumnIndex("_data"));
                    Log.d("path", path);
                    uploadFile(path);
                    cursor.close();
                    return;

                }
                break;
            default:
                break;
        }
    }
    public void get(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);
        appService.getData().enqueue(new Callback<List<App>>() {
            @Override
            public void onResponse(Call<List<App>> call, Response<List<App>> response) {
                List<App> body = response.body();
                for (App app : body) {
                    Log.d("GET", app.toString());
                }
            }

            @Override
            public void onFailure(Call<List<App>> call, Throwable t) {

            }
        });
    }

    /**
     * 获取服务器中，第一页数据
     * @param view
     */
    public void one(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);
        appService.getDataByPage("1").enqueue(new Callback<List<App>>() {
            @Override
            public void onResponse(Call<List<App>> call, Response<List<App>> response) {
                List<App> body = response.body();
                for (App app : body) {
                    Log.d("服务器中第一页数据", app.toString());
                }
            }

            @Override
            public void onFailure(Call<List<App>> call, Throwable t) {

            }
        });
    }

    /**
     * 获取服务器中，第二页数据
     * @param view
     */
    public void two(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);
        appService.getDataByPage("2").enqueue(new Callback<List<App>>() {
            @Override
            public void onResponse(Call<List<App>> call, Response<List<App>> response) {
                List<App> body = response.body();
                for (App app : body) {
                    Log.d("GET", app.toString());
                }
            }

            @Override
            public void onFailure(Call<List<App>> call, Throwable t) {

            }
        });
    }

    /**
     * POST提交数据
     * @param view
     */
    public void post(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);

        // 设置请求内容
        App app = new App("年少有为", "20", "3.0");
        appService.post(app).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.d("POST请求响应", string);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });
    }

    /**
     * 发送带参数的GET请求
     * @param view
     */
    public void getAndParam(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);
        appService.getDataAndUserToken("aaa", "bbb").enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                ResponseBody body = response.body();
                if (body != null) {
                    try {
                        Log.d("带参数的GET请求", body.string());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    /**
     * 带静态消息头的请求
     * @param view
     */
    public void staticHeader(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);
        appService.statusHeader().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.d("带静态消息头的请求", string);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }



    /**
     * 带动态消息头的请求
     * @param view
     */
    public void dynamicHeader(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);
        appService.dynamicHeader("Redmi K30 Pro").enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    String string = response.body().string();
                    Log.d("带静态消息头的请求", string);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    public void delete(View view) {
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        AppService appService = build.create(AppService.class);
        appService.deleteById().enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    ResponseBody string = response.body();
                    if (string != null) {
                        Log.d("带静态消息头的请求", string.string());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

    public void upload(View view) {
        // 兼容的写法
        Intent intent = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"*/*");
        startActivityForResult(intent, FROMAIBUM);
//        Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
//        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // 指定只显示图片
//        intent.setType("image/*");
//        startActivityForResult(intent, FROMAIBUM);
    }

    private void uploadFile(String path) {
        File file = new File(path);
        RequestBody body = RequestBody.create(MediaType.parse("image/*"), file);
        // 和后端约定好的key
        MultipartBody.Part by = MultipartBody.Part.createFormData("file", file.getName(), body);

        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://test.ziyia.cn/")
                .addConverterFactory(GsonConverterFactory.create())
                .client(new OkHttpClient.Builder().retryOnConnectionFailure(true)
                        .writeTimeout(20, TimeUnit.SECONDS)
                        .readTimeout(20, TimeUnit.SECONDS)
                        .connectTimeout(20, TimeUnit.SECONDS)
                        .build())
                .build();
        AppService appService = build.create(AppService.class);
        appService.upload(by).enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                try {
                    ResponseBody string = response.body();
                    if (string != null) {
                        Log.d("文件上传", string.string());
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {
                t.printStackTrace();
            }
        });

    }


    interface AppService {
        @GET("get_data.json")
         Call<List<App>> getData();

        @GET("{page}/get_data.json")
        Call<List<App>> getDataByPage(@Path("page")String page);

        @GET("request.php")
        Call<ResponseBody> getDataAndUserToken(@Query("u")String u, @Query("t") String t);

        @DELETE("request.php")
        Call<ResponseBody> deleteById();

        @POST("request.php")
        Call<ResponseBody> post(@Body App app);

        @Headers({"User-Agent: okhttp", "Cache-Control: max-age=0"})
        @GET("request.php")
        Call<ResponseBody> statusHeader();

        @GET("request.php")
        Call<ResponseBody> dynamicHeader(@Header("User-Agent") String userAgent);

        // 有问题
        @Multipart
        @POST("upload.php")
        Call<ResponseBody> upload(@Part MultipartBody.Part f);
    }


}

